package com.ygqh.baby.observer;

import com.ygqh.baby.ao.*;
import com.ygqh.baby.constant.Constant;
import com.ygqh.baby.handler.PreBalanceHandler;
import com.ygqh.baby.model.BalanceDetailForTask;
import com.ygqh.baby.po.YgAgent;
import com.ygqh.baby.po.YgAgentInviteRecord;
import com.ygqh.baby.po.YgOrder;
import com.ygqh.baby.po.YgUser;
import com.ygqh.baby.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

/**
 * @Author: sunshuo
 * @Date: 2019/4/10 15:56
 * @Version: 1.0
 */
@Component
public class InformObserver implements Observer {

	private final Logger logger = LoggerFactory.getLogger(InformObserver.class);

	@Autowired
	private YgInformService ygInformService;
	@Autowired
	private YgOrderService ygOrderService;
	@Autowired
	private YgUserService ygUserService;
	@Autowired
	private YgAgentInviteRecordService ygAgentInviteRecordService;
	@Autowired
	private PreBalanceHandler preBalanceHandler;
	@Autowired
	private YgAgentService ygAgentService;

	@Override
	public void update(Observable o, Object arg) {
		logger.info("InformObserver.update: {}", arg);
		OrderPayModel model = arg != null ? (OrderPayModel) arg : null;
		if (model == null || model.getOrderId() == null) {
			logger.info(o.getClass().getName() + ": orderCode 为空");
			return;
		}
		YgOrder order = ygOrderService.findOrderDetailByOrderId(model.getOrderId());
		if (order == null || !Constant.YIJIADIAN_PLATFORM_NO.equals(order.getPlatformNo())) {
			return;
		}
		try {
			YgUser orderUser = ygUserService.findById(order.getUserId());
			processForUserAgent(orderUser, order.getPlatformNo());

			YgAgentInviteRecord record = ygAgentInviteRecordService.findRecordForYijiandian(orderUser.getId());
			if (record != null) {
				YgUser inviteUser = ygUserService.findById(record.getUserId());
				if (inviteUser == null) {
					return;
				}
				// 给上级用户发送粉丝下单通知
				if (UserType.UserAgent.equals(orderUser.getUserType())) {
					YgAgent orderAgent = ygAgentService.findValidByUserId(orderUser.getId(), UserType.UserAgent);
					// 下单人为代理时，上级邀请人抽取30%的佣金，否则上级邀请人抽取100%佣金
					preBalanceHandler.processOrderDetailPriceForShare(order,
							orderAgent.getLevelRate().multiply(BigDecimal.valueOf(0.3)));
				}
				if (UserType.UserAgent.equals(inviteUser.getUserType())) {
					YgAgent inviteAgent = ygAgentService.findValidByUserId(inviteUser.getId(), UserType.UserAgent);
					preBalanceHandler.processOrderDetailPriceForShare(order, inviteAgent.getLevelRate());
				}
				BigDecimal incomePrice = getIncomePrice(order);
				String content;
				if (UserType.UserAgent.equals(inviteUser.getUserType())) {
					content = "此单预计可得" + incomePrice + "元";
				} else {
					content = "成为会员此单预计可得" + incomePrice + "元";
				}
				ygInformService.asyncSendInform(inviteUser.getId(), content, InformType.OrderSuccess,
						"OrderSuccess");
				processForUserAgent(inviteUser, order.getPlatformNo());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void processForUserAgent(YgUser user, String platformNo) {
		if (UserType.UserAgent.equals(user.getUserType())) {
			return;
		}
		// 还不是代理会员，校验会员资质
		ResponseEntity response = ygAgentInviteRecordService.
				validateUserForUserAgent(user, platformNo, SalesPlatform.Yijiadian);
		if (!response.isSuccess()) {
			return;
		}
		// 达到会员资质，发送站内消息
		ygInformService.asyncSendInform(user.getId(), null, InformType.MemberChance,
				"MemberChance");
	}

	private BigDecimal getIncomePrice(YgOrder order) {
		List<BalanceDetailForTask> detailList = preBalanceHandler.preBalancePretreatment(order);
		return detailList.stream().map(o -> o.getBalancePrice(RebateType.Forever, order.getPlatformNo()))
				.reduce(BigDecimal::add).get();
	}
}
